let logger = require('pomelo-logger').getLogger("gameData");
const enumeration = require('../constant/enumeration');
const gameConfig = require('../gameComponent/gameConfig');
const userDao = require('../dao/userDao');
const commonDao = require('../dao/commonDao');
const code = require('../constant/code');
const userInfoServices = require('../services/userInfoServices');
const moment = require('moment');
//游戏相关功能服务类
class gameServices {


    //普通房间支付
    static async roomPay(userArr, gameRule, chairCount, roomID, payUserID, gameType) {

        //普通场支付
        let payDiamond = gameConfig.oneUserDiamondCount(gameRule.bureau, gameRule.gameType, gameRule.maxPlayerCount);
        if (gameRule.payType === enumeration.roomPayType.AAZHIFU) {
            let saveDataArr = [];
            let curUserList = [];
            for (let key in userArr) {
                let user = userArr[key];
                if (user) {
                    if (user.chairID >= chairCount) {
                        continue;
                    } else {
                        curUserList.push(key);
                    }
                }
            }
            if (curUserList.length === 0) return;
            let curGold = Math.ceil(payDiamond / (curUserList.length)) || 1;
            for (let i = 0; i < curUserList.length; i++) {
                saveDataArr.push({
                    matchData: { uid: curUserList[i] },
                    saveData: { $inc: { gold: -curGold } }
                });
            }
            logger.info(`[${roomID}][pay] hall room pay payType = ${gameRule.payType} payUserList = [${curUserList}] payDiamond = ${curGold}`);
            let newUserDataArr = await userDao.updateUserDataArr(saveDataArr);
            for (let i = 0; i < newUserDataArr.length; ++i) {
                let updateUserData = newUserDataArr[i];
                if (!updateUserData) continue;
                if (!!updateUserData.frontendId) {
                    userInfoServices.updateUserDataNotify(updateUserData.uid, updateUserData.frontendId, { gold: updateUserData.gold }).catch((err) => { logger.error(err.stack) });
                }
            }
        } else if (gameRule.payType === enumeration.roomPayType.WOZHIFU) {
            return await gameServices.userPay(payUserID, payDiamond, roomID, -1, gameType);
        }
    }

    //联盟房间支付
    static async unionRoomPay(unionOwnerUid, gameRule, roomID, unionID, gameType, isUser = false) {

        let payDiamond = gameConfig.oneUserDiamondCount(gameRule.bureau, gameRule.gameType, gameRule.maxPlayerCount);
        //保存砖石
        let saveTeamData = { $inc: { "diamondCount": payDiamond } };
        let dateTime = moment().format('YYYY-MM-DD');
        await commonDao.findOneAndUpdateEx('teamDataModel', { unionID, dateTime }, saveTeamData);

        let matchData = { uid: unionOwnerUid };
        // 首局开局时检测金币是否足够，不够则解散房间
        matchData.gold = { $gte: payDiamond };
        let userData = await userDao.updateUserData(matchData, { $inc: { gold: -payDiamond } });
        if (!userData) {
            logger.info(`[${roomID}][pay] union room pay payType = ${gameRule.payType} unionOwnerUid = [${unionOwnerUid}] payDiamond = ${payDiamond} fail`, true);
            return code.NOT_ENOUGH_GOLD;
        } else {
            if (!!userData.frontendId) {
                userInfoServices.updateUserDataNotify(userData.uid, userData.frontendId, { gold: userData.gold }).catch((err) => { logger.error(err.stack) });
            }
            //保存钻石记录
            let day = moment().format("YYYY-MM-DD");
            let avatar = userData.avatar;
            let nickname = userData.nickname;
            let detailData = { unionID, day, roomID, gameType, avatar, nickname, uid: unionOwnerUid, count: payDiamond, createTime: Date.now() };
            await commonDao.createData('userPayDetailModel', detailData);
            delete detailData['count'];
            detailData.$inc = { count: payDiamond };
            await commonDao.findOneAndUpdateEx('userPayModel', { day, unionID, uid: unionOwnerUid }, detailData, { upsert: true, new: true });
            //保存联盟砖石
            let curDay = moment().format("YYYY-MM");
            let saveData = { unionID, day: curDay, year: moment().format("YYYY"), month: moment().format("MM") };
            saveData.$inc = { count: payDiamond };
            await commonDao.findOneAndUpdateEx('unionPayModel', { day: curDay, unionID }, saveData, { upsert: true, new: true });

            logger.info(`[${roomID}][pay] union room pay payType = ${gameRule.payType} unionOwnerUid = [${unionOwnerUid}] payDiamond = ${payDiamond} allCount = ${userData.gold}  success`);
            return code.OK;
        }
    }


    static async userPay(uid, payDiamond, roomID, unionID, gameType) {

        let matchData = { uid: uid };
        matchData.gold = { $gte: payDiamond };
        let userData = await userDao.updateUserData(matchData, { $inc: { gold: -payDiamond } });
        if (!userData) {
            logger.info(`[${roomID}][pay] user pay  uid = [${uid}] payDiamond = ${payDiamond} fail`);
            return code.NOT_ENOUGH_GOLD;
        } else {
            if (!!userData.frontendId) {
                userInfoServices.updateUserDataNotify(userData.uid, userData.frontendId, { gold: userData.gold }).catch((err) => { logger.error(err.stack) });
            }
            //保存钻石记录
            let day = moment().format("YYYY-MM-DD");
            let avatar = userData.avatar;
            let nickname = userData.nickname;
            let detailData = { unionID, day, roomID, gameType, avatar, nickname, uid, count: payDiamond, createTime: Date.now() };
            await commonDao.createData('userPayDetailModel', detailData);
            delete detailData['count'];
            detailData.$inc = { count: payDiamond };
            await commonDao.findOneAndUpdateEx('userPayModel', { day, unionID, uid: uid }, detailData, { upsert: true, new: true });
            //保存联盟砖石
            let curDay = moment().format("YYYY-MM");
            let saveData = { unionID, day: curDay, year: moment().format("YYYY"), month: moment().format("MM") };
            saveData.$inc = { count: payDiamond };
            await commonDao.findOneAndUpdateEx('unionPayModel', { day: curDay, unionID }, saveData, { upsert: true, new: true });
            logger.info(`[${roomID}][pay] user pay uid = [${uid}] payDiamond = ${payDiamond} allCount = ${userData.gold} success`);
            return code.OK;
        }
    }

    //判断是否可以创建
    static async checkGold(userInfo, gameRule) {

        let payDiamond = 0;
        if (gameRule.payType === enumeration.roomPayType.AAZHIFU) {
            let bureau = parseInt(gameRule.bureau) || 1;
            //  let payDiamond = (gameRule.perDiamond || gameRule.payDiamond) || 1;
            payDiamond = bureau;
        } else {
            payDiamond = gameConfig.oneUserDiamondCount(gameRule.bureau, gameRule.gameType, gameRule.maxPlayerCount);
        }
        if (userInfo.gold < payDiamond) {
            return true;
        } else {
            return false;
        }
    }


}


module.exports = gameServices;